import os
import openpyxl


def process_qichezhijia_excel(folder_path):
    # 获取文件夹中的文件列表
    file_list = os.listdir(folder_path)

    # 遍历文件列表
    for file_name in file_list:
        # 拼接文件路径
        file_path = os.path.join(folder_path, file_name)
        output_file = os.path.splitext(file_name)[0] + '.txt'  # 输出文件名，默认为将原Excel文件名改为txt格式
        output_file_path = os.path.join(folder_path, output_file)
        # 判断文件类型（这里假设文件类型为Excel）
        if file_name.endswith('.xlsx') or file_name.endswith('.xls'):
            # 读取Excel文件
            workbook = openpyxl.load_workbook(file_path)

            worksheet = workbook.active

            header_row = worksheet[1]
            car_name_list = [cell.value for cell in header_row[1:] if cell.value is not None]
            car_name_list = [value for value in car_name_list]

            print(car_name_list)
            result = ''
            empty_cells = []
            for row in worksheet.iter_rows(min_row=1, max_row=worksheet.max_row + 1, min_col=2, max_col=2):
                cell = row[0]
                if cell.value is None or cell.value == "":
                    empty_cells.append(cell.coordinate)

            # print(empty_cells)
            row_numbers = []
            for cell_pos in empty_cells:
                row_numbers.append(int(cell_pos[1:]))
            # print(row_numbers)

            bigTitle_list = [worksheet.cell(row=row_number, column=1).value for row_number in row_numbers]
            bigTitle_list = bigTitle_list[:-1]

            for i in range(len(row_numbers) - 1):

                first_column = worksheet['A']
                first_column_data = []
                column_data = [cell.value for cell in
                               first_column[row_numbers[i]:row_numbers[i + 1] - 1]]  # 从起始行到结束行获取数据
                first_column_data.extend(column_data)

                print(bigTitle_list[i])
                for j, col_data in enumerate(
                        worksheet.iter_cols(min_row=row_numbers[i] + 1, max_row=row_numbers[i + 1] - 1, min_col=2,
                                            max_col=len(car_name_list) + 1,
                                            values_only=True)):

                    merged_list = [str(item1) + '是' + str(item2) for item1, item2 in zip(first_column_data, col_data)]
                    temp = str(car_name_list[j]) + '的' + str(bigTitle_list[i]) + '信息为'
                    merged_list.insert(0, temp)
                    merged_string = merged_list[0] + ', '.join(merged_list[1:]) + '。'
                    merged_string = merged_string.replace("-", "无").replace("●", "标配").replace("○", "选配")
                    print(merged_string)
                    result += merged_string
                result += '\n'
            with open(output_file_path, 'w') as file:
                file.write(result)


